package com.siyoumi.app.modules.act.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siyoumi.app.entity.ActSet;
import com.siyoumi.app.modules.act.service.SvcActSet;
import com.siyoumi.app.service.ActSetService;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/xadmin/act/act__item__list")
public class act__item__list
        extends AdminApiController {
    @GetMapping()
    public XReturn index() {
        setPageTitle("活动-列表");

        ActSetService app = ActSetService.getBean();

        InputData inputData = InputData.fromRequest();
        JoinWrapperPlus<ActSet> query = SvcActSet.getBean().listQuery(inputData);

        IPage<ActSet> page = new Page<>(inputData.getPageIndex(), inputData.getPageSize());
        //list
        IPage<ActSet> pageData = app.get(page, query);
        List<ActSet> list = pageData.getRecords();
        long count = pageData.getTotal();

        List<Map<String, Object>> listData = list.stream().map(entity ->
        {
            HashMap<String, Object> data = new HashMap<>(entity.toMap());
            data.put("id", entity.getKey());

            // 活动时间验证
            String errmsgDate = "";
            XReturn rDate = entity.validDate();
            if (rDate.err()) {
                errmsgDate = rDate.getErrMsg();
            }
            data.put("errmsg_date", errmsgDate);

            //测试状态
            String status = entity.test() ? "测试" : "正式";
            data.put("__status", status);

            return data;
        }).collect(Collectors.toList());

        getR().setData("list", listData);
        getR().setData("count", count);
        return getR();
    }


    //删除
    @Transactional
    @PostMapping("/del")
    public XReturn del(String[] ids) {
        SvcActSet app = SvcActSet.getBean();
        return app.delete(Arrays.asList(ids));
    }

    //删除测试数据
    @Transactional
    @GetMapping("/del_test_data")
    public XReturn deleteTestData() {
        String actId = input("act_id");
        if (XStr.isNullOrEmpty(actId)) {
            return EnumSys.MISS_VAL.getR("miss act_id");
        }

        SvcActSet app = SvcActSet.getBean();
        return app.deleteTestData(actId);
    }
}
